package com.zhixing.web.api.aspect;

import com.zhixing.web.api.annotation.Log;
import com.zhixing.web.api.dataobject.untils.ResultVoUtil;
import com.zhixing.web.common.utils.ArgsUtil;
import com.zhixing.web.common.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * @author dzh
 * @version 1.0.0.05020
 * <p>project: d-blog</p>
 * <p>created time: 2022/05/02 15:17</p>
 * <p>describe: 记录操作日志</p>
 * <p>remarks: </p>
 **/
@Slf4j
@Aspect
@Component
public class LogAspect {

    @Pointcut("@annotation(com.zhixing.web.api.annotation.Log)")
    public void verify() {}


    @Around("verify()")
    public Object doVerify(ProceedingJoinPoint proceedingJoinPoint) {

        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();

        String value = signature.getMethod().getAnnotation(Log.class).value();

        try {

            // 执行方法
            Object returnValue = proceedingJoinPoint.proceed();

            log.info("[操作记录] ## 时间: {} ## 模块:{} ## 方法: {} ## 参数: {} ## 返回值: {}" ,
                    DateUtil.getCurrentTime(), value, signature.getMethod(),
                    ArgsUtil.getParamsToString(proceedingJoinPoint), returnValue);

            // 返回方法返回值
            return returnValue;

        } catch (Throwable throwable) {

            log.error("[系统异常] ## 时间: {} ## 模块:{} ## 方法: {} ## 参数: {} ## 异常:" ,
                    DateUtil.getCurrentTime(), value, signature.getMethod(),
                    ArgsUtil.getParamsToString(proceedingJoinPoint), throwable);

            return ResultVoUtil.error(-1, "系统异常");
        }
    }
}